package org.dromara.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import org.dromara.app.appParams.AppDetailByIdParams;
import org.dromara.app.appParams.AppPageParams;
import org.dromara.app.appReturn.AppDaRenInfo;
import org.dromara.app.appReturn.AppMyUserInfo;
import org.dromara.app.cssUtils.CssUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.dromara.app.domain.bo.SkFansUserBo;
import org.dromara.app.domain.vo.SkFansUserVo;
import org.dromara.app.domain.SkFansUser;
import org.dromara.app.mapper.SkFansUserMapper;
import org.dromara.app.service.ISkFansUserService;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 粉丝列Service业务层处理
 *
 * @author Evacuation
 * @date 2024-08-07
 */
@RequiredArgsConstructor
@Service
public class SkFansUserServiceImpl implements ISkFansUserService {

    private final SkFansUserMapper baseMapper;

    /**
     * 查询粉丝列
     *
     * @param id 主键
     * @return 粉丝列
     */
    @Override
    public SkFansUserVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询粉丝列列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 粉丝列分页列表
     */
    @Override
    public TableDataInfo<SkFansUserVo> queryPageList(SkFansUserBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SkFansUser> lqw = buildQueryWrapper(bo);
        Page<SkFansUserVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的粉丝列列表
     *
     * @param bo 查询条件
     * @return 粉丝列列表
     */
    @Override
    public List<SkFansUserVo> queryList(SkFansUserBo bo) {
        LambdaQueryWrapper<SkFansUser> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SkFansUser> buildQueryWrapper(SkFansUserBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SkFansUser> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, SkFansUser::getUserId, bo.getUserId());
        lqw.eq(bo.getGzUserId() != null, SkFansUser::getGzUserId, bo.getGzUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getCreateDepe()), SkFansUser::getCreateDepe, bo.getCreateDepe());
        return lqw;
    }

    /**
     * 新增粉丝列
     *
     * @param bo 粉丝列
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SkFansUserBo bo) {
        SkFansUser add = MapstructUtils.convert(bo, SkFansUser.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改粉丝列
     *
     * @param bo 粉丝列
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SkFansUserBo bo) {
        SkFansUser update = MapstructUtils.convert(bo, SkFansUser.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SkFansUser entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除粉丝列信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 关注用户
     */
    @Override
    public void getLike(AppDetailByIdParams params, HttpServletRequest req) {
        Long userId = CssUtils.getUserId(req);
        List<SkFansUser> list = baseMapper.selectList(
            new QueryWrapper<SkFansUser>().lambda()
                .eq(SkFansUser::getUserId,userId)
                .eq(SkFansUser::getGzUserId,params.getId())
        );
        if (list.size()>0){
            baseMapper.delete( new QueryWrapper<SkFansUser>().lambda()
                .eq(SkFansUser::getUserId,userId)
                .eq(SkFansUser::getGzUserId,params.getId()));
        }else{
            SkFansUser sk = new SkFansUser();
            sk.setUserId(userId);
            sk.setGzUserId(params.getId());
            baseMapper.insert(sk);
        }
    }

    /**
     * 关注用户列表
     *
     * @param params
     * @param req
     * @return
     */
    @Override
    public List<AppDaRenInfo> getLikeList(AppPageParams params, HttpServletRequest req) {
        List<AppDaRenInfo> list = baseMapper.getLikeList(params,CssUtils.getUserId(req));
        if (list.size()>0){
            for(AppDaRenInfo app:list){
                if (app.getBirthday() != null && !app.getBirthday().equals("")) {
                    LocalDate bir = LocalDate.parse(app.getBirthday() + "-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                    Period age = Period.between(bir, LocalDate.now());
                    app.setAge(age.getYears() + "");
                }
            }
        }
        return list;
    }

    /**
     * 我的粉丝列表
     */
    @Override
    public List<AppDaRenInfo> getFansList(AppPageParams params, HttpServletRequest req) {
        Long userId = CssUtils.getUserId(req);
        params.setUserId(userId);
        //关注我的
        List<AppDaRenInfo> list = baseMapper.getFansList(params);
        //我关注的
        List<AppDaRenInfo> list1 = baseMapper.getLikeListAll(userId);
        Map<Long,AppDaRenInfo> map = list1.stream().collect(Collectors.toMap(AppDaRenInfo::getUserId,AppDaRenInfo->AppDaRenInfo));
        for(AppDaRenInfo app:list){
            if (map.get(app.getUserId())!=null){
                app.setIsLike(1);
            }else{
                app.setIsLike(0);
            }
        }
        return list;
    }

}
